<?php

/* 
 * Edit by shengxin
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/EmptyPHP.php to edit this template
 */
use api\mall\model\OnlineModel;
function xx_array_to_map($arr,$key){
    $map = [];
    foreach ($arr as $v) {  
        $map[$v[$key]] = $v;  
    }
    return $map;
}

/**
 * 记录用户在线时间
 */
function online_record($userId){
    $model = new OnlineModel();
    $online = $model->where('user_id',$userId)->order('id desc')->find();
    $now = time();
    $today = date('Y-m-d');
    if(empty($online)||$online->date!=$today){
        $model->insert(['user_id'=>$userId,'sync_time'=>$now,'total_time'=>0,'date'=>$today]);
    }else{
        $last_time = $online->sync_time;
        $delta = $now-$last_time;
        $update = ['sync_time'=>$now];
        if($delta<100){
            //间隔时长太长,不正常
            $update['total_time']=$online->total_time + $delta;
        }
        $model->where('user_id',$userId)->update($update);
    }
}

function cmf_random_number($len = 6)
{
    $chars    = [
         "1", "2", "3", "4", "5", "6", "7", "8", "9"
    ];
    $charsLen = count($chars) - 1;
    shuffle($chars);    // 将数组打乱
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}